<template>
  <div class="system-edit-role-container">
    <el-dialog :close-on-click-modal="false" :title="(acType == 'auth' ? '分配数据权限' : acType == 'edit' ? '修改角色' : '添加角色')"
      v-model="isShowDialog" width="769px">
      <el-form ref="formRef" :model="formData" :rules="rules" size="default" label-width="90px">
        <el-row :gutter="35">
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
            <el-form-item label="角色名称" prop="roleName">
              <el-input v-model="formData.roleName" placeholder="请输入角色名称" :disabled="acType == 'auth'"
                clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
            <el-form-item label="显示顺序" prop="roleSort">
              <el-input-number v-model="formData.roleSort" :min="0" controls-position="right" placeholder="请输入排序"
                class="w100" :disabled="acType == 'auth'" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
            <el-form-item label="角色状态">
              <el-switch v-model="formData.status" :active-value="0" :inactive-value="1" inline-prompt active-text="正常"
                inactive-text="停用" :disabled="acType == 'auth'"></el-switch>
            </el-form-item>
          </el-col>
          <el-col v-if="acType !== 'auth'" :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
            <el-form-item label="菜单权限">
              <el-row :gutter="35">
                <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
                  <el-checkbox v-model="menuExpand" @change="handleCheckedTreeExpand($event)">展开/折叠</el-checkbox>
                  <el-checkbox v-model="menuNodeAll" @change="handleCheckedTreeNodeAll($event)">全选/全不选</el-checkbox>
                  <el-checkbox v-model="menuCheckStrictly" @change="handleCheckedTreeConnect($event)">父子联动</el-checkbox>
                </el-col>
                <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
                  <el-tree :data="menuData" ref="menuRef" :props="menuProps" :default-checked-keys="formData.menuIds"
                    node-key="menuId" show-checkbox class="menu-data-tree tree-border"
                    :check-strictly="!menuCheckStrictly" />
                </el-col>
              </el-row>
            </el-form-item>
          </el-col>
          <el-col class="mb20" v-if="acType == 'auth'">
            <el-form-item label="权限范围">
              <el-select size="default" v-model="formDataAuth.dataScope" clearable>
                <el-option label="全部数据权限" :value="1" />
                <el-option label="自定义数据权限" :value="2" />
                <el-option label="本部门数据权限" :value="3" />
                <el-option label="本部门及以下数据权限" :value="4" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col v-if="acType == 'auth' && formDataAuth.dataScope == 2" :xs="24" :sm="24" :md="24" :lg="24" :xl="24"
            class="mb20">
            <el-form-item label="部门权限">
              <el-row :gutter="35">
                <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
                  <el-checkbox v-model="menuExpand" @change="handleCheckedTreeExpandDept($event)">展开/折叠</el-checkbox>
                  <el-checkbox v-model="menuNodeAll" @change="handleCheckedTreeNodeAllDept($event)">全选/全不选</el-checkbox>
                  <el-checkbox v-model="menuCheckStrictly" @change="handleCheckedTreeConnect($event)">父子联动</el-checkbox>
                </el-col>
                <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
                  <el-tree :data="deptData" ref="deptRef" :props="{ disabled: 'a' }"
                    :default-checked-keys="formDataAuth.depts" node-key="id" show-checkbox
                    class="menu-data-tree tree-border" :check-strictly="!menuCheckStrictly" />
                </el-col>
              </el-row>
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="onCancel" size="default">取 消</el-button>
          <el-button type="primary" @click="onSubmit" size="default" :loading="loading">{{ acType == 'auth' ? '确定' :
            acType == 'edit' ? '修改' : '添加' }}</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import { reactive, toRefs, defineComponent, ref, getCurrentInstance, unref } from 'vue';
import { addRoleApi, editRoleApi, detailsRoleApi, scopeRoleApi, treeRoleDeptApi } from "@/api/auth/role";
import { ElMessage } from "element-plus";
import { treeMenuListApi } from '@/api/auth/menu'
// import {refreshBackEndControlRoutes} from "/@/router/backEnd";
interface DialogRow {
  roleId: number;
  roleName: string;
  status: number;
  roleSort: number;
  dataScope: number,
  menuIds: Array<number>
}
interface RoleState {
  loading: boolean;
  isShowDialog: boolean;
  formData: DialogRow;
  menuExpand: boolean;
  menuNodeAll: boolean;
  menuCheckStrictly: boolean;
  menuProps: {
    children: string;
    label: string;
  };
  rules: object;
}

export default defineComponent({
  name: 'systemEditRole',
  props: {
    acType: {
      type: String,
      default: () => 'add'
    },
  },
  setup(props, { emit }) {
    const { proxy } = getCurrentInstance() as any;
    const formRef = ref<HTMLElement | null>(null);
    const menuRef = ref();
    const deptRef = ref();
    const state = reactive<RoleState>({
      loading: false,
      isShowDialog: false,
      formData: {
        roleId: null,
        roleName: '',
        status: 0,
        roleSort: 0,
        dataScope: null,
        menuIds: [],
      },
      // 表单校验
      rules: {
        roleName: [
          { required: true, message: "角色名称不能为空", trigger: "blur" },
        ],
        roleSort: [
          { required: true, message: "显示顺序不能为空", trigger: "blur" },
        ]
      },
      menuExpand: false,
      menuNodeAll: false,
      menuCheckStrictly: false,
      menuProps: {
        children: 'children',
        label: 'menuName',
      },
    });
    const deptData = ref([])
    const menuData = ref([])
    // 修改数据权限
    const formDataAuth = reactive({
      roleId: null,
      dataScope: null,
      depts: [],
    })

    // 打开弹窗
    const openDialog = (acType, row?: DialogRow) => {
      resetForm();
      if (row) {
        state.formData = row
        let obj = {
          id: row.roleId
        }
        console.log(props);
        if (acType == 'edit') {
          detailsRoleApi(obj).then((res: any) => {
            if (res.data) {
              state.formData.menuIds = res.data.checkedKeys
              menuData.value = res.data.menus
            }
          })
        } else if (acType == 'auth') {
          formDataAuth.dataScope = row.dataScope
          formDataAuth.roleId = row.roleId
          treeRoleDeptApi(obj).then((res: any) => {
            if (res.data) {
              formDataAuth.depts = res.data.checkedKeys
              deptData.value = res.data.deptTree
            }
          })
        }
      } else {
        if (menuData.value.length == 0) treeMenuListApi({}).then(res => {
          menuData.value = res.data
        })
      }
      state.isShowDialog = true;
    };



    // 关闭弹窗
    const closeDialog = () => {
      state.isShowDialog = false;
    };
    // 取消
    const onCancel = () => {
      closeDialog();
    };
    // 新增
    const onSubmit = () => {
      const formWrap = unref(formRef) as any;
      if (!formWrap) return;
      formWrap.validate((valid: boolean) => {
        if (valid) {
          state.loading = true;
          if (props.acType !== 'auth') {
             state.formData.menuIds = getMenuAllCheckedKeys();
            if (props.acType == 'add') {
              //添加
              addRoleApi(state.formData).then(() => {
                ElMessage.success('角色添加成功');
                closeDialog(); // 关闭弹窗
                resetMenuSession()
                emit('getRoleList')
              }).finally(() => {
                state.loading = false;
              })
            } else if (props.acType == 'edit') {
              //修改
              editRoleApi(state.formData).then(() => {
                ElMessage.success('角色修改成功');
                closeDialog(); // 关闭弹窗
                resetMenuSession()
                emit('getRoleList')
              }).finally(() => {
                state.loading = false;
              })
            }
          } else {
            if (formDataAuth.dataScope == 2) formDataAuth.depts = getMenuAllCheckedKeysDept();
            else formDataAuth.depts = []
            console.log(formDataAuth);
            scopeRoleApi(formDataAuth).then(() => {
              ElMessage.success('权限修改成功');
              closeDialog(); // 关闭弹窗
              resetMenuSession()
              emit('getRoleList')
            }).finally(() => {
              state.loading = false;
            })
          }
        }
      });
    };
    const resetForm = () => {
      state.menuCheckStrictly = false;
      state.menuExpand = false;
      state.menuNodeAll = false;
      state.formData = {
        roleId: null,
        roleName: '',
        status: 0,
        roleSort: 0,
        menuIds: [],
        dataScope: null
      }
    };


    /** 树权限（展开/折叠）*/
    const handleCheckedTreeExpand = (value: any) => {
      let treeList = menuData.value
      for (let i = 0; i < treeList.length; i++) {
        menuRef.value.store.nodesMap[treeList[i].menuId].expanded = value;
      }
    }

    /** 树权限（全选/全不选） */
    const handleCheckedTreeNodeAll = (value: any) => {
      menuRef.value.setCheckedNodes(value ? menuData.value : []);
    }

    /** 树权限（父子联动） */
    const handleCheckedTreeConnect = (value: any) => {
      state.menuCheckStrictly = value ? true : false;
    }

    /** 所有菜单节点数据 */
    function getMenuAllCheckedKeys() {
      // 目前被选中的菜单节点
      let checkedKeys = menuRef.value.getCheckedKeys();
      // 半选中的菜单节点
      // let halfCheckedKeys = menuRef.value.getHalfCheckedKeys();
      checkedKeys.unshift.apply(checkedKeys);
      return checkedKeys;
    }

    // 重置菜单session
    const resetMenuSession = () => {
      // refreshBackEndControlRoutes();
    };


    // 部门的-----------
    /** 树权限（展开/折叠）*/
    const handleCheckedTreeExpandDept = (value: any) => {
      let treeList = deptData.value;
      for (let i = 0; i < treeList.length; i++) {
        deptRef.value.store.nodesMap[treeList[i].id].expanded = value;
      }
    }

    /** 树权限（全选/全不选） */
    const handleCheckedTreeNodeAllDept = (value: any) => {
      deptRef.value.setCheckedNodes(value ? deptData.value : []);
    }
    /** 所有菜单节点数据 */
    function getMenuAllCheckedKeysDept() {
      // 目前被选中的菜单节点
      let checkedKeys = deptRef.value.getCheckedKeys();
      checkedKeys.unshift.apply(checkedKeys);
      return checkedKeys;
    }
    return {
      openDialog,
      closeDialog,
      onCancel,
      onSubmit,
      menuRef,
      formRef,
      formDataAuth,
      deptRef,
      deptData,
      menuData,
      handleCheckedTreeExpand,
      handleCheckedTreeNodeAll,
      handleCheckedTreeConnect,
      resetMenuSession,
      handleCheckedTreeExpandDept,
      handleCheckedTreeNodeAllDept,
      getMenuAllCheckedKeysDept,
      ...toRefs(state),
    };
  },
});
</script>

<style scoped lang="scss">
.tree-border {
  margin-top: 5px;
  border: 1px solid #e5e6e7 !important;
  border-radius: 4px;
}

.system-edit-role-container {
  .menu-data-tree {
    border: var(--el-input-border, var(--el-border-base));
    border-radius: var(--el-input-border-radius, var(--el-border-radius-base));
    padding: 5px;
  }
}
</style>
